import * as React from 'react';
import {
  StyleSheet,
  View,
  Image,
  TextInput,
  Text,
  Alert,
  Button,
  NativeModules,
} from 'react-native';

import LoadingUtil from '../../util/LoadingUtil';

const TitleBar = () => {
  return (
    <View>
      <Image
        style={{
          width: 25,
          height: 25,
        }}
        source={require('../../../public/assets/images/title_logo.png')}
      />
    </View>
  );
};

const RemoteApi = NativeModules.RemoteApi;

const formData = {
  username: 'admin',
  password: '123456',
};

const LoginForm = ({navigation}) => {
  const [form, setForm] = React.useState(formData);

  const onSubmit = () => {
    LoadingUtil.showLoading('登录中...');

    console.log(form);
    if (form.username === '') {
      Alert.alert('请输入用户名');
      return;
    }
    if (form.password === '') {
      Alert.alert('请输入密码');
      return;
    }
    // 登录请求
    RemoteApi.login(form, (success, msg) => {
      LoadingUtil.dismissLoading();
      if (success) {
        // 此处跳转使用`replace` 而非`navigate` ,否则在Home页点击back时,又会回到Login
        navigation.replace('Home');
        return;
      }
      Alert.alert(msg);
    });
  };

  return (
    <View>
      <View
        style={{
          alignItems: 'center',
        }}>
        <Image
          style={{
            width: 150,
            height: 150,
          }}
          source={require('../../../public/assets/images/title_logo.png')}
        />
      </View>

      <View
        style={{
          paddingHorizontal: 20,
        }}>
        <View>
          <Text>用户:</Text>
          <TextInput
            placeholder="请输入用户名"
            onChangeText={text => setForm({...form, username: text})}
            value={form.username}
          />
        </View>

        <View>
          <Text>密码:</Text>
          <TextInput
            placeholder="请输入密码"
            onChangeText={text => setForm({...form, password: text})}
            value={form.password}
          />
        </View>

        <View>
          <Button title="登录" onPress={() => onSubmit()} />
        </View>
      </View>
    </View>
  );
};

const LoginScreen = ({navigation}) => {
  return (
    <View>
      <TitleBar />
      <LoginForm navigation={navigation} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  horizontal: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    padding: 10,
  },
});

export default LoginScreen;
